package com.mj.base;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.google.gson.Gson;
import com.mj.model.system.User;
import com.mj.service.system.UserService;
import com.mj.util.Constants;

/**
 * 基类 (待扩展)
 *@ClassName:BaseController.java
 *@author dsc
 *@date 2017年7月21日
 *@Description TODO
 *
 */
public class BaseController {
	protected Gson gson;
	protected Logger log = Logger.getLogger(this.getClass());
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	@Autowired
    private UserService userService;
	@ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
	    this.request = request;
	    this.response = response;
    }

	
	public static final Boolean SUCCESS = true;
	public static final Boolean ERROR = false;
	
	/**
	 * 返回json字符串
	 * @param obj
	 * @return
	 */
	public String renderJson(Object obj){
		JSONObject text = JSONObject.fromObject(obj);
		return text.toString();
	}
	
	/**
	 * 数组返回json字符串
	 * @param obj
	 * @return
	 */
	public String renderJsonArray(Object obj){
		JSONArray arr = JSONArray.fromObject(obj);
		return arr.toString();
	}
	
	/**
	 * 数据表格返回json字符串
	 * @param list
	 * @return
	 */
	public String renderJsonGrid(Object list,int totalNum){
		JSONObject obj = new JSONObject();
        obj.put("rows", list); //这里的 rows 和total 的key 是固定的
        obj.put("total", totalNum);
		return obj.toString(); 
	}
	
	/**
	 * 获取当前用户
	 * @return
	 */
	public User getUser(){
		 Subject currentUser = SecurityUtils.getSubject();
	     User user = userService.selectByName(currentUser.getPrincipals().toString());
	     return user;
	}

}
